package gwtappcontainer.server.apis.home;

import gwtappcontainer.server.apis.APIBase;
import gwtappcontainer.server.apis.APIException;
import gwtappcontainer.server.apis.admin.Roles.Role;
import gwtappcontainer.server.apis.geolocation.GeoLocationAPI;
import gwtappcontainer.shared.apis.APIResponse;
import gwtappcontainer.shared.apis.APIResponse.Status;

import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiMethod.HttpMethod;
import com.google.appengine.api.users.User;

@Api (name = "home", 
	scopes = { "https://www.googleapis.com/auth/userinfo.email" }
)
public class HomeAPI extends APIBase {
	
	@ApiMethod(httpMethod = HttpMethod.GET, path = "geticons")
	public APIResponse getIcons() {
		
		try {
		
			HomeRepository homeRepository = new HomeRepository();
			
			String html = homeRepository.getAllIconsAndURLsAsHtml();
			
			return new APIResponse(Status.SUCCESS, html);													
		} catch (Exception ex) {
			return new APIResponse(ex);
		} 
	}	
	
	@ApiMethod(httpMethod = HttpMethod.GET, path = "getuser")
	public APIResponse getLoggedInUser(User user) {		
		
		try {						
			if (null == user)
				throw new APIException(Status.ERROR_LOGIN_REQUIRED, "User not logged in");
			
			return new APIResponse(Status.SUCCESS, user.getEmail());
			
		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}
	
	@ApiMethod(httpMethod = HttpMethod.PUT, path = "seticons")
	public APIResponse setIcons(@Named("iconshtml") String html, User user) {
		
		try {
			//only allowed for DEVELOPER
			ensureRole(user, Role.DEVELOPER);			
			
			HomeRepository homeRepository = new HomeRepository();
			
			html = homeRepository.setAllIconsAndURLsAsHtml(html);
			
			return new APIResponse(Status.SUCCESS, html);			
			
		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}
	
	@ApiMethod(httpMethod = HttpMethod.GET, path = "getlocation")
	public APIResponse getLocation(HttpServletRequest req) {
		
		try {
		
			GeoLocationAPI api = new GeoLocationAPI();
			
			APIResponse response = api.getLocation(req);
						
			return response;
		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}
}
